<template>
  <div class="login-page">
    <div class="login-container">
      <el-card class="box-card">
        <div class="text-center">
          <h3>会员登录</h3>
          <el-radio-group v-model="loginMode" style="margin-bottom: 20px;">
            <el-radio-button label="account">账号密码登录</el-radio-button>
            <el-radio-button label="phone">手机验证码登录</el-radio-button>
          </el-radio-group>
        </div>
        <el-form :model="form" :rules="rules" ref="loginForm" label-position="top">
          <template v-if="loginMode === 'account'">
            <el-form-item label="账号" prop="memberAccount">
              <el-input v-model="form.memberAccount" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="memberPassword">
              <el-input v-model="form.memberPassword" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="form.remember">记住密码</el-checkbox>
            </el-form-item>
          </template>

          <template v-else>
            <el-form-item label="手机号" prop="memberPhone">
              <el-input v-model="form.memberPhone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="验证码" prop="code">
              <el-input v-model="form.code" placeholder="请输入验证码" style="width: 60%;"></el-input>
              <el-button :disabled="countdown > 0" @click="sendCode" style="margin-left: 10px;">
                {{ countdown > 0 ? countdown + '秒后重试' : '发送验证码' }}
              </el-button>
            </el-form-item>
          </template>

          <el-form-item>
            <div class="button-group">
              <el-button type="success" @click="onSubmit">登录</el-button>
              <el-button type="primary" @click="toAdminLogin">转到管理员登录</el-button>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="msg" class="error-msg">{{ msg }}</div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()

const loginMode = ref('account')
const form = ref({
  memberAccount: '',
  memberPassword: '',
  remember: false,
  memberPhone: '',
  code: ''
})

const rules = ref({
  memberAccount: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  memberPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  memberPhone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

const loginForm = ref(null)
const msg = ref('')

const countdown = ref(0)
let timer = null
let isSending = false  // 防抖锁

const sendCode = () => {
  if (isSending) return

  if (!form.value.memberPhone) {
    ElMessage.warning('请输入手机号')
    return
  }

  if (countdown.value > 0) {
    ElMessage.warning('请不要重复发送验证码')
    return
  }

  isSending = true
  startCountdown()

  axios.get('/server/memberPhoneLogin/sendLoginCheckCode', {
    params: {
      memberPhone: form.value.memberPhone
    }
  })
      .then(response => {
        const data = response.data
        if (data.code === 200) {
          ElMessage.success('验证码已发送')
        } else {
          ElMessage.error(data.message || '验证码发送失败')
          countdown.value = 0
        }
      })
      .catch(() => {
        ElMessage.error('验证码请求失败')
        countdown.value = 0
      })
      .finally(() => {
        isSending = false
      })
}

const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const onSubmit = () => {
  loginForm.value.validate((valid) => {
    if (valid) {
      if (loginMode.value === 'account') {
        axios.post('/server/Member/MemberLogin', {
          memberAccount: form.value.memberAccount,
          memberPassword: form.value.memberPassword,
        })
            .then(response => {
              const token = response.data.data.token;
              localStorage.setItem('token', token);
              const data = response.data
              if (data.code === 200) {
                ElMessage.success('登录成功')
                router.push('/MemberMain/MemberHome')
              } else {
                msg.value = data.message || '登录失败'
              }
            })
            .catch(() => {
              msg.value = '登录请求失败'
            })
      } else {
        axios.post('/server/memberPhoneLogin/checkLoginCode', {
          memberPhone: form.value.memberPhone,
          code: form.value.code
        })
            .then(response => {
              const data = response.data
              if (data.code === 200) {
                ElMessage.success('登录成功')
                router.push('/MemberMain/MemberHome')
              } else {
                msg.value = data.message || '登录失败'
              }
            })
            .catch(() => {
              msg.value = '登录请求失败'
            })
      }
    }
  })
}

const toAdminLogin = () => {
  router.push('/AdminLogin')
}
</script>

<style scoped>
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.login-page {
  width: 100vw;
  height: 100vh;
  background: url('/img/background.jpeg') no-repeat center center;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-container {
  width: 400px;
}
.box-card {
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.4);
}
.button-group {
  display: flex;
  justify-content: space-between;
}
.error-msg {
  color: red;
  text-align: center;
  margin-top: 20px;
}
</style>
